/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("upper_ftpmachiningcenter",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.System.IServices;
using FluentFTP;
using System.IO;
using SysIO = System.IO;
using System.Net;
using VOL.Core.Enums;
using VOL.Core.Filters;
using VOL.System.Services;
using Org.BouncyCastle.Asn1.Ocsp;
using VOL.WebApi.Controllers;
using System.Text;
using NPOI.SS.UserModel;
using System.Linq;
using ClosedXML.Excel;


namespace VOL.System.Controllers
{
    public partial class upper_ftpmachiningcenterController
    {
        private readonly Iupper_ftpmachiningcenterService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        private FileHelper _fileHelper;
        NpoiService _excelService;
        private readonly string _uploadPath;
        private readonly string _templatePath;
        [ActivatorUtilitiesConstructor]
        public upper_ftpmachiningcenterController(
            Iupper_ftpmachiningcenterService service,
            IHttpContextAccessor httpContextAccessor,
            FileHelper fileHelper
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
            _excelService = new NpoiService();
            _fileHelper= fileHelper;
            _uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "Upload");
            _templatePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates");
        }

        private string _FtpPath = "ftp://localhost/";
        private string ftpUsername = "admin";
        private string ftpPassword = "123456";
        /// <summary>
        /// 获取FTP文件，文件夹
        /// </summary>
        /// <param name="remoteFolderPath"></param>
        /// <returns></returns>
        [ApiActionPermission(ActionPermissionOptions.Search)]
        [HttpPost, Route("GetFileList")]
        public IActionResult GetFileList([FromBody] string remoteFolderPath = "")
        {
            // 在这里编写代码获取文件列表，并返回数据
            var fileList = GetFiles(remoteFolderPath);
            return new JsonResult(fileList);
        }

        private List<TreeNode> GetFiles(string remoteFolderPath = "")
        {
            List<TreeNode> fileList = new List<TreeNode>();

            var directoryContents = _fileHelper.GetFileList(remoteFolderPath);

                    foreach (var ftpListItem in directoryContents)
                    {
                        if (ftpListItem.IsDirectory)
                        {
                            //显示文件夹
                            var item = new TreeNode() { Title = ftpListItem.Name, Field = "文件夹", Href = remoteFolderPath+"/"+ ftpListItem.Name };
                            fileList.Add(item);

                        }
                        else
                        {
                            //显示文件
                            var item = new TreeNode() { Title = ftpListItem.Name, Field = "文件", Href = remoteFolderPath + "/"+ ftpListItem.Name };
                            fileList.Add(item);
                            //Console.WriteLine($"[F] {ftpListItem.Name}");
                        }
                    }

                //client.Disconnect();
            //}

            return fileList;
        }
        #region 项目导入

        [HttpGet("template")]
        public IActionResult DownloadTemplate()
        {
            try
            {
                var templateFile = Path.Combine(_templatePath, "ProjectImportTemplate.xlsx");

                // 如果模板文件不存在，创建新的模板
                if (!SysIO.File.Exists(templateFile))
                {
                    CreateTemplateFile(templateFile);
                }

                var memory = new MemoryStream();
                using (var stream = new FileStream(templateFile, FileMode.Open))
                {
                    stream.CopyTo(memory);
                }
                memory.Position = 0;

                return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "项目导入模板.xlsx");
            }
            catch (Exception ex)
            {
               //_logger.LogError(ex, "下载模板失败");
                return StatusCode(500, new { message = "下载模板失败：" + ex.Message });
            }
        }

        private void CreateTemplateFile(string filePath)
        {
            using var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add("项目导入模板");

            // 设置列标题
            worksheet.Cell(1, 1).Value = "项目名称";
            worksheet.Cell(1, 2).Value = "项目描述";
            worksheet.Cell(1, 3).Value = "项目类型";
            worksheet.Cell(1, 4).Value = "负责人";
            worksheet.Cell(1, 5).Value = "开始日期";
            worksheet.Cell(1, 6).Value = "结束日期";

            // 设置列宽
            worksheet.Column(1).Width = 20;
            worksheet.Column(2).Width = 30;
            worksheet.Column(3).Width = 15;
            worksheet.Column(4).Width = 15;
            worksheet.Column(5).Width = 15;
            worksheet.Column(6).Width = 15;

            // 设置标题行样式
            var headerRange = worksheet.Range(1, 1, 1, 6);
            headerRange.Style.Fill.BackgroundColor = XLColor.LightGray;
            headerRange.Style.Font.Bold = true;
            headerRange.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

            // 添加示例数据
            worksheet.Cell(2, 1).Value = "示例项目";
            worksheet.Cell(2, 2).Value = "这是一个示例项目";
            worksheet.Cell(2, 3).Value = "开发项目";
            worksheet.Cell(2, 4).Value = "张三";
            worksheet.Cell(2, 5).Value = DateTime.Now.ToString("yyyy-MM-dd");
            worksheet.Cell(2, 6).Value = DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd");

            // 添加数据验证
            var typeList = new[] { "开发项目", "维护项目", "测试项目", "其他" };
            //var typeValidation = worksheet.DataValidation.Add(worksheet.Range(2, 3, 1000, 3));
            //typeValidation.List(typeList);

            // 添加日期格式
            worksheet.Column(5).Style.DateFormat.Format = "yyyy-MM-dd";
            worksheet.Column(6).Style.DateFormat.Format = "yyyy-MM-dd";

            // 保存模板文件
            workbook.SaveAs(filePath);
        }


        //[ApiActionPermission(ActionPermissionOptions.Upload)]
        [HttpPost, Route("FileUploadProject")]
        public async Task<IActionResult> FileUploadProject([FromForm] IFormFile file)
        {
            //try
            //{
            //    if (file == null || file.Length == 0)
            //    {
            //        return BadRequest(new { message = "未选择文件" });
            //    }

            //    // 验证文件大小（100MB）
            //    if (file.Length > 100 * 1024 * 1024)
            //    {
            //        return BadRequest(new { message = "文件大小不能超过100MB" });
            //    }

            //    var extension = Path.GetExtension(file.FileName).ToLower();

            //    // 验证文件类型
            //    if (!IsValidFileType(extension))
            //    {
            //        return BadRequest(new { message = "不支持的文件类型" });
            //    }
            //    return Ok(new
            //    {
            //        code = 200,
            //        message = "项目导入成功",
            //        data = new { projectId = "新项目ID" }
            //    });
            //    // 生成唯一文件名
            //    var fileName = $"{Guid.NewGuid()}{extension}";
            //    var filePath = Path.Combine(_uploadPath, fileName);

            //    //// 保存文件
            //    //using (var stream = new FileStream(filePath, FileMode.Create))
            //    //{
            //    //    await file.CopyToAsync(stream);
            //    //}

            //    //// 根据文件类型处理不同的导入逻辑
            //    //if (IsProjectFile(extension))
            //    //{
            //    //    return await HandleProjectFileImport(filePath);
            //    //}
            //    //else if (IsExcelFile(extension))
            //    //{
            //    //    return await HandleExcelImport(filePath);
            //    //}

            //    return BadRequest(new { message = "不支持的文件类型" });
            //}
            //catch (Exception ex)
            //{
            //    //_logger.LogError(ex, "项目导入失败");
            //    return StatusCode(500, new { message = "导入失败：" + ex.Message });
            //}
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { message = "未选择文件" });
                }

                // 验证文件大小（100MB）
                if (file.Length > 100 * 1024 * 1024)
                {
                    return BadRequest(new { message = "文件大小不能超过100MB" });
                }

                var extension = Path.GetExtension(file.FileName).ToLower();

                // 验证文件类型
                if (!IsValidFileType(extension))
                {
                    return BadRequest(new { message = "不支持的文件类型" });
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}{extension}";
                var filePath = Path.Combine(_uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 根据文件类型处理不同的导入逻辑
                if (IsProjectFile(extension))
                {
                    return await HandleProjectFileImport(filePath);
                }
                else if (IsExcelFile(extension))
                {
                    return await HandleExcelImport(filePath);
                }

                return BadRequest(new { message = "不支持的文件类型" });
            }
            catch (Exception ex)
            {
                //_logger.LogError(ex, "项目导入失败");
                return StatusCode(500, new { message = "导入失败：" + ex.Message });
            }
        }

        private bool IsValidFileType(string extension)
        {
            var validExtensions = new[] { ".zip", ".rar", ".xlsx", ".xls" };
            return validExtensions.Contains(extension);
        }

        private bool IsProjectFile(string extension)
        {
            return extension == ".zip" || extension == ".rar";
        }

        private bool IsExcelFile(string extension)
        {
            return extension == ".xlsx" || extension == ".xls";
        }

        private async Task<IActionResult> HandleProjectFileImport(string filePath)
        {
            try
            {
                // TODO: 实现项目文件导入逻辑
                // 1. 解压文件
                // 2. 验证项目结构
                // 3. 保存到数据库

                return Ok(new
                {
                    code = 200,
                    message = "项目导入成功",
                    data = new { projectId = "新项目ID" }
                });
            }
            catch (Exception ex)
            {
                //_logger.LogError(ex, "项目文件导入失败");
                return StatusCode(500, new { message = "项目文件导入失败：" + ex.Message });
            }
            finally
            {
                //// 清理临时文件
                //if (System.IO.File.Exists(filePath))
                //{
                //    System.IO.File.Delete(filePath);
                //}
            }
        }

        private async Task<IActionResult> HandleExcelImport(string filePath)
        {
            try
            {
                //using var workbook = new XLWorkbook(filePath);
                //var worksheet = workbook.Worksheet(1);
                //var rows = worksheet.RowsUsed();
                var importCount = 0;

                //// 跳过标题行
                //foreach (var row in rows.Skip(1))
                //{
                //    var projectData = new
                //    {
                //        Name = row.Cell(1).Value.ToString(),
                //        Description = row.Cell(2).Value.ToString(),
                //        Type = row.Cell(3).Value.ToString(),
                //        Manager = row.Cell(4).Value.ToString(),
                //        StartDate = DateTime.Parse(row.Cell(5).Value.ToString()),
                //        EndDate = DateTime.Parse(row.Cell(6).Value.ToString())
                //    };

                //    // TODO: 将数据保存到数据库
                //    // await _projectService.CreateProjectAsync(projectData);
                    importCount++;
                //}

                return Ok(new
                {
                    code = 200,
                    message = "Excel导入成功",
                    data = new { importCount }
                });
            }
            catch (Exception ex)
            {
           
                return StatusCode(500, new { message = "Excel导入失败：" + ex.Message });
            }
            finally
            {
                //// 清理临时文件
                //if (System.IO.File.Exists(filePath))
                //{
                //    System.IO.File.Delete(filePath);
                //}
            }
        }
        #endregion
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="files"></param>
        /// <param name="remoteFolder"></param>
        /// <returns></returns>
        [ApiActionPermission(ActionPermissionOptions.Upload)]
        [HttpPost, Route("FileUpload")]
        public IActionResult FileUpload([FromForm] List<IFormFile> fileInput, string remoteFolder)
        {
            //if (remoteFolder==null)
            //{
            //    remoteFolder = "未知";
            //}
            //remoteFolder = remoteFolder.Trim();
            if (fileInput == null || fileInput.Count == 0)
            {
           //     return BadRequest(new { Code = "Error", Msg = "请选择上传的文件" });
                return new JsonResult(new { Code = "Error", Message = "请选择上传的文件！" });
            }
            //if (string.IsNullOrEmpty(remoteFolder))
            //{
            //    return BadRequest(new { Code = "Error", Msg = "请输入远程文件夹名称" });
            //}
            if (string.IsNullOrEmpty(remoteFolder))
            {
                //  return JsonResult(new { Code = "Error", Msg = "请选择工单类型" });
                return new JsonResult(new { Code = "Error", Message = "请选择工单类型！" });
            }
            upper_ftpmachiningcenter machiningCenterProgramSheet = new upper_ftpmachiningcenter();
            List<upper_ftpprogram> upper_Ftpprograms = new List<upper_ftpprogram>();
            PLAN_WORK_ORDER pLAN_WORK_ORDER = new PLAN_WORK_ORDER();
            pLAN_WORK_ORDER.OrderType = remoteFolder;

            int upload = -1;
            List<TreeNode> list = GetFiles("");

           

            //将Excel文件信息传到数据库
            foreach (var item in fileInput)
            {
                string extension = Path.GetExtension(item.FileName);
                if (extension == ".xls" || extension == ".xlsx")
                {
                    if (item != null && item.Length > 0)
                    {
                        using (var stream = item.OpenReadStream())
                        {
                            
                            _excelService.ReadExcelForMachingCenterFileNew(item.FileName, machiningCenterProgramSheet, upper_Ftpprograms, pLAN_WORK_ORDER, stream);

                            upload = _service.CreateModelByExcelNew(machiningCenterProgramSheet, upper_Ftpprograms,pLAN_WORK_ORDER);

                            //_excelService.InsertDataWithTransaction<MachiningCenterProgramSheet, ProgramInfo>(machiningCenterProgramSheet, ////machiningCenterProgramSheet.ProgramInfo);
                        }
                    }
                }
            }

            foreach (var treeNode in list)
            {
                if (treeNode.Field != "文件夹")
                {
                    continue;
                }

                // #region FTP文件操作  文件后处理自动产生这里不需要上传

                remoteFolder = treeNode.Href + "/" + machiningCenterProgramSheet.mold_number;
                if (string.IsNullOrEmpty(remoteFolder))
                {
                    return BadRequest(new { Code = "Error", Msg = "请输入远程文件夹名称" });
                }



                // 检查文件夹是否存在，如果不存在则创建文件夹
                if (!DirectoryExists(_FtpPath, ftpUsername, ftpPassword, remoteFolder))
                {
                    CreateDirectory(_FtpPath, ftpUsername, ftpPassword, remoteFolder);
                }

                foreach (var item in fileInput)
                {
                    _fileHelper.UploadFile(item, remoteFolder);
                }
            }

            if (upload==-1)
            {
                return new JsonResult(new { Code = "ERROR",Message="上传失败！" });
            }
            if (upload == -2)
            {
                return new JsonResult(new { Code = "ERROR", Message = "上传失败！【刀具名称格式如\"Ø35R5\" 第一个字母为Ø第二为数字, 第三为R 第四为数字】" });
            }
            if (upload == -3)
            {
                return new JsonResult(new { Code = "ERROR", Message = "上传失败！【R角大于设备刀具最大R】" });
            }
            return new JsonResult(new { Code = "OK",Message="上传成功！" });
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="files"></param>
        /// <param name="remoteFolder"></param>
        /// <returns></returns>
        [ApiActionPermission(ActionPermissionOptions.Upload)]
        [HttpPost, Route("FileUploadByWorkOrderId")]
        public IActionResult FileUploadByWorkOrderId([FromForm] List<IFormFile> fileInput, string workOrderId,int index)
        {
            if (!int.TryParse(workOrderId,out var param))
            {
                return BadRequest(new {Code="Error",Msg="订单号错误"});
            }

            if (fileInput == null || fileInput.Count == 0)
            {
                return BadRequest(new { Code = "Error", Msg = "请选择上传的文件" });
            }

            int upload = -1;
            List<TreeNode> list = GetFiles("");
            upper_work_order  workOrder= _service.GetWorkOrderEntity(workOrderId);


            foreach (var treeNode in list)
            {
                if (treeNode.Field!="文件夹")
                {
                    continue;
                }

                #region FTP文件操作  文件后处理自动产生这里不需要上传
                var remoteFolder = treeNode.Href+"/"+ workOrder.work_order_number;
                if (string.IsNullOrEmpty(remoteFolder))
                {
                    return BadRequest(new { Code = "Error", Msg = "请输入远程文件夹名称" });
                }
              


                // 检查文件夹是否存在，如果不存在则创建文件夹
                if (!DirectoryExists(_FtpPath, ftpUsername, ftpPassword, remoteFolder))
                {
                    CreateDirectory(_FtpPath, ftpUsername, ftpPassword, remoteFolder);
                }

                try
                {
                    foreach (var item in fileInput)
                    {
                        _fileHelper.UploadFile(item, remoteFolder);

                        List<upper_file> files= _service.GetDataFiles();
                        Parallel.ForEach(files, file =>
                        {
                            var filePath = Path.Combine(_fileHelper.GetRootPath() + remoteFolder, file.file_name+".CNC");
                            try
                            {
                                if (!SysIO.File.Exists(filePath))
                                {
                                    using (var stream = new FileStream(filePath, FileMode.CreateNew))
                                    {
                                        stream.Write(Encoding.UTF8.GetBytes(file.file_content));
                                    }
                                }
                               
                            }
                            catch
                            {

                            }
                          
                        });

                      
                        //_service.Context
                        //var filePath = Path.Combine(_fileHelper.GetRootPath() + remoteFolder, file.FileName);
                        //+remoteFolder;
                    }

                }
                catch (Exception ex) 
                {
                    return BadRequest(new { Code = "Error", Message = "数据库更新成功，但上传文件过程中出错，上传失败！" });
                }
                #endregion
            }
            upload = _service.ChangeText(workOrderId, index, Path.GetFileNameWithoutExtension(fileInput[0].FileName));

           

            //将Excel文件信息传到数据库

            if (upload == -1)
            {
                return new JsonResult(new { Code = "ERROR", Message = "上传失败！" });
            }

         
            return new JsonResult(new { Code = "OK", Message = "上传成功！" });
        }




        private bool DirectoryExists(string ftpHost, string ftpUsername, string ftpPassword, string remoteFolderPath)
        {
            
            try
            {
                return _fileHelper.FolderExists(remoteFolderPath);
            }
            catch 
            {
                return false;
            }
        }

        private void CreateDirectory(string ftpHost, string ftpUsername, string ftpPassword, string remoteFolderPath)
        {
             _fileHelper.CreateFolder(remoteFolderPath);
        }
    }

    public class TreeNode
    {
        public List<TreeNode> Children { get; set; } = new List<TreeNode>();
        public string Type { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Field { get; set; }
        public string Href { get; set; }
    }
}
